package com.ebao.tec.controller;

import com.ebao.tec.entity.MyResult;
import com.ebao.tec.service.UserService;
import com.ebao.tec.entity.User;
import com.ebao.tec.entity.UserExample;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.security.provider.MD4;

import java.util.List;

import static com.ebao.tec.constant.Code.*;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param user
     * @return
     */
    @RequestMapping("/login")
    public MyResult login(User user) {
        System.out.println(user);
        if(user==null || Strings.isBlank(user.getUserPwd())){
            return MyResult.error(MSG_PARAMETER_INVALID);
        }
        md5ToPwd(user);
        UserExample userExample = new UserExample();
        userExample.createCriteria()
                .andUserNameEqualTo(user.getUserName())
                .andUserPwdEqualTo(user.getUserPwd());
        List<User> users = userService.selectByExample(userExample);
        if(users.isEmpty()) {
            return MyResult.error(MSG_USER_ERROR);
        } else {
            return MyResult.ok().put(DATA, users.get(0));
        }
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @RequestMapping("/register")
    public MyResult register(User user) {
        if(user==null || Strings.isBlank(user.getUserPwd())){
            return MyResult.error(MSG_PARAMETER_INVALID);
        }
        md5ToPwd(user);
        int i = userService.insert(user);
        if(i > 0) {
            return MyResult.ok();
        } else {
            return MyResult.error();
        }
    }

    /**
     * 判断用户名是否重复
     * @param userName
     * @return
     */
    @RequestMapping("/nameRepeat/{userName}")
    public MyResult nameRepeat(@PathVariable("userName") String userName) {
        if(Strings.isBlank(userName)){
            return MyResult.error(MSG_PARAMETER_INVALID);
        }
        UserExample userExample = new UserExample();
        userExample.createCriteria()
                .andUserNameEqualTo(userName);
        List<User> users = userService.selectByExample(userExample);
        if(users.isEmpty()) {
            return MyResult.ok();
        } else {
            return MyResult.error(MSG_USERNAME_EXIST);
        }
    }

    /**
     * 用户密码加密
     * @param user
     * @return
     */
    private void md5ToPwd(User user){
        String pwdStr = user.getUserPwd();
        String md5Pwd = DigestUtils.md5DigestAsHex(pwdStr.getBytes());
        user.setUserPwd(md5Pwd);
    }

}
